﻿using Net7Docker.FrameWork;
using System.Data;
using System.Data.SqlClient;
using System.Runtime.CompilerServices;
using System.Text.Json.Serialization;

namespace Net7Docker.Common;

/// <summary>
/// Sql帮助类
/// </summary>
public class SqlHelper
{
    public T Find<T>(int id)
    {
        //获取到T的类型==》拿到对象
        Type type = typeof(T);

        //声明返回类型的实例，方便最后将对象返回出去
        T t = default(T);

        //获取到type的所有字段==>并且以逗号连接
        var columnStr = string.Join(",", type.GetProperties().Select(p => $"[{p.Name}]"));

        var sql = $"SELECT {columnStr} FROM {type.Name} WHERE ID={id} ";

        //链接数据库读取数据

        using (SqlConnection conn = new SqlConnection(ConfigurationManager.SqlConnectString))
        {
            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {
                if (conn.State != ConnectionState.Open)
                    conn.Open();
                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        t = (T)Activator.CreateInstance(type);
                        foreach (var prop in type.GetProperties())
                        {
                            prop.SetValue(t, reader[prop.Name] is DBNull ? null : reader[prop.Name]);
                        }
                    }
                }
            }
        }
        return t;
    }
}

public class Company
{
    public string Name { get; set; }

    public DateTime CreateTime { get; set; }

    public int CreatorId { get; set; }

    public Nullable<int> LastModifierId { get; set; }

    public DateTime? LastModifyTime { get; set; }

    public override string ToString()
    {
        return $"{this.Name}\t{this.CreateTime}\t{this.CreatorId}\t{this.LastModifierId}\t{this.LastModifyTime}";
    }
}
